#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from Utils.Logger import logger
from Utils.Timer import timer
from openpyxl.styles import PatternFill
import openpyxl


class ExcelParser:
    """解析Excel表，提供操作Excel表格的基础方法"""
    @timer(tracer=False)
    def __init__(self, file_path):
        self.file_path = file_path
        self.file_name = self.file_path.split('\\')[-1]
        self.workbook = openpyxl.load_workbook(self.file_path, data_only=True)
        self.worksheet_names = self.workbook.sheetnames

    def get_worksheet(self, sheet_name):
        try:
            return self.workbook[sheet_name]
        except KeyError:
            logger.error('工作簿[{0}]的工作表[{1}]不存在'.format(self.file_path, sheet_name))

    def set_cell_background_color(self, sheet_name, row, column, fg_color):
        fill = PatternFill(fgColor=fg_color, fill_type='solid')
        ws = self.get_worksheet(sheet_name)
        ws.cell(row=row, column=column).fill = fill

    @timer(tracer=False)
    def save_workbook(self):
        try:
            self.workbook.save(self.file_path)
        except PermissionError:
            logger.error('表格[{0}]正在被使用，无法保存，请关闭表格重试'.format(self.file_name))
